import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rabbit_mobile/i18n/strings.g.dart';
import 'package:rabbit_mobile/provide/riverpod_provider.dart';
import 'package:rabbit_mobile/view/Category/models/category_model.dart';
import 'package:rabbit_mobile/view/Home/models/home_model.dart';
import 'package:rabbit_mobile/service/home.api.dart';
import 'package:rabbit_mobile/view/Login/models/login_model.dart';
import 'package:rabbit_mobile/view/goods_details/models/goods_details_model.dart';

import '../view/Mine/models/user_profile_model.dart';
import '../view/Oder_payment/models/payments_model.dart';
import '../view/ShoppingCart/models/shopping_cart_model.dart';

// 首頁請求
final homeProvider = FutureProvider<HomeModel>((ref) async {
  return await HomeAPI.homeFetch(); // 异步请求数据
});

// 一級分類
class CategoryNotifier extends StateNotifier<AsyncValue<CategoryFirstLevel>> {
  CategoryNotifier() : super(const AsyncValue.loading());

  /// 一級分類加載數據
  Future fetchCategories() async {
    try {
      final categoryData = await CategoryApi.categoryFetch();
      state = AsyncValue.data(categoryData); // 存儲加載的數據
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}

// 二級分類
class CategorySecondsLevelNotifier extends StateNotifier<AsyncValue<CategorySecondsLevel>> {
  CategorySecondsLevelNotifier() : super(const AsyncValue.loading());

  /// 二級數據分類加載
  Future fetchCategoriesSecondsLevel(String id) async {
    try {
      final categorySecondsData = await CategoryApi.categorySecondsLevelFetch(id);
      state = AsyncValue.data(categorySecondsData);
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}

// 登錄
class LoginNotofier extends StateNotifier<AsyncValue<LoginModel>> {
  LoginNotofier() : super(const AsyncValue.loading());

  Future fetchLogin(dynamic data) async {
    try {
      final loginData = await LoginApi.loginFetch(data);
      state = AsyncValue.data(loginData);
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}

// 商品詳情
class GoodsDetailsNotifier extends StateNotifier<AsyncValue<GoodsDetailsModel>> {
  GoodsDetailsNotifier() : super(const AsyncValue.loading());

  Future fetchGoodsDetails(String id) async {
    try {
      final goodsDetailsData = await GoodsDetailsApi.goodsDetailsFetch(id);
      state = AsyncValue.data(goodsDetailsData);
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}

// 商品規格選擇
class GoodsDetailsSpecsNotifier extends StateNotifier<List<GoodsDetailsSpecs2Model>> {
  GoodsDetailsSpecsNotifier(List<GoodsDetailsSpecs2Model> state) : super(state);

  void updateGoodsDetailsSpec(String specName, String valueName) {
    state = state.map((specItem) {
      if (specItem.name == specName) {
        final updatedValues = specItem.values.map((valueItem) {
          if (valueItem.name == valueName) {
            // 切换选中状态
            return valueItem.copyWith(isSelected: !valueItem.isSelected);
          } else {
            return valueItem.copyWith(isSelected: false); // 取消其他选项的选中状态
          }
        }).toList();
        return specItem.copyWith(values: updatedValues); // 返回更新后的规格项
      }
      return specItem; // 其他规格项不变
    }).toList(); // 返回新的列表
  }
}

// 購物車反選/選擇
class ShoppingCartIsSelectedNotifier extends StateNotifier<List<ShoppingCartValidsModel>> {
  ShoppingCartIsSelectedNotifier(List<ShoppingCartValidsModel> initialData) : super(initialData);

  void setInitialData(List<ShoppingCartValidsModel> data) {
    state = data;
  }

  /// 判斷是否全部已選中
  bool get isAllSelected => state.every((item) => item.selected);

  double get selectedTotalPrice {
    return double.parse(
      state.where((item) => item.selected).fold(0.0, (sum, item) {
        final price = double.tryParse(item.price) ?? 0.0;
        return sum + price * item.count;
      }).toStringAsFixed(2),
    );
  }

  /// 單個商品選中/取消選中
  void updateShoppingCartIsSelected(String id) {
    final newState = state.map((item) {
      if (item.id == id) {
        return item.copyWith(selected: !item.selected);
      }
      return item;
    }).toList();

    if (state != newState) {
      state = newState;
    }
  }

  /// 全選/反選
  void toggleAllSelected() {
    final allSelected = state.every((item) => item.selected);
    final newState = state.map((item) {
      return item.copyWith(selected: allSelected);
    }).toList();

    if (state != newState) {
      state = newState;
    }
  }

  /// 全選/反選
  void toggleAllSelected2() {
    final newState = state.map((item) {
      return item.copyWith(selected: !item.selected);
    }).toList();

    if (state != newState) {
      state = newState;
    }
  }

  /// 商品數量增
  void goodsCountAdd(String id) {
    final newState = state.map((item) {
      if (item.id == id) {
        return item.copyWith(count: item.count + 1);
      }
      return item;
    }).toList();

    if (state != newState) {
      state = newState;
    }
  }

  /// 商品數量減
  void goodsCountMul(String id) {
    final newState = state.map((item) {
      if (item.id == id && item.count > 1) {
        return item.copyWith(count: item.count - 1);
      }
      return item;
    }).toList();

    if (state != newState) {
      state = newState;
    }
  }

  /// 刪除購物車
  void deleteShoppingCart(String id) {
    final newState = state.where((item) => item.id != id).toList();

    if (state != newState) {
      state = newState;
    }
  }
}

/// 加入購物車
class AddedShoppingCartNotifier extends StateNotifier<AsyncValue> {
  AddedShoppingCartNotifier() : super(const AsyncValue.loading());

  Future fetchAddedShoppingCart(dynamic data) async {
    try {
      final addedShoppingCart = ShoppingCartApi.shoppingCartFetch(data);
      return addedShoppingCart;
    } catch (e) {
      debugPrint('$e');
    }
  }
}

/// get shopping cart api data
class GetShoppingCartNotifier extends StateNotifier<AsyncValue<ShoppingCartModel>> {
  GetShoppingCartNotifier() : super(const AsyncValue.loading());

  Future fetchGetShoppingCart() async {
    try {
      final data = await GetShoppingCartApi.getShoppingCartFetch();
      state = AsyncValue.data(data);
    } catch (e) {
      debugPrint('$e');
      if (e is DioException && e.error == 'unauthorized') {
        state = AsyncValue.error('unauthorized', StackTrace.current);
      } else {
        state = AsyncValue.error(e, StackTrace.current);
      }
    }
  }
}

/// change shoppingCart state
class ChangeShoppingCartStateNotifier extends StateNotifier<AsyncValue> {
  ChangeShoppingCartStateNotifier() : super(const AsyncValue.loading());

  Future fetchChangeShoppingCart(dynamic data) async {
    try {
      final changeShoppingCartData =
          await ChangeShoppingCartApi.changeShoppingCartFetch({data.selected, data.count, data.id});
      state = AsyncValue.data(changeShoppingCartData);
    } catch (e) {
      debugPrint('$e');
    }
  }
}

// 語言包切換
class LocaleNotifier extends StateNotifier<AppLocale> {
  LocaleNotifier() : super(LocaleSettings.currentLocale);

  void changeLocale(AppLocale locale) {
    LocaleSettings.setLocale(locale);
    state = locale; // 通知所有监听者更新
  }
}

/// get shopping cart total count
class GetShoppingCartCountNotifier extends StateNotifier<AsyncValue<GetShoppingCartCountModel>> {
  final Ref ref;

  GetShoppingCartCountNotifier(this.ref) : super(const AsyncValue.loading());

  Future fetchGetShoppingCartCount() async {
    try {
      final getShoppingCartCountData = await GetShoppingCartCountApi.getShoppingCartCountFetch();
      state = AsyncValue.data(getShoppingCartCountData);
      ref.read(shoppingCartGoodsTotalCount.notifier).state = getShoppingCartCountData.count;
    } catch (e) {
      debugPrint('$e');
    }
  }
}

/// guess you like
class GetGuessYouLikeNotifier extends StateNotifier<AsyncValue<GetGuessYouLikeModel>> {
  GetGuessYouLikeNotifier() : super(const AsyncValue.loading());

  Future fetchGetGuessYouLike() async {
    try {
      final getGuessYouLikeData = await GetGuessYouLike.getGuessYouLikeFetch();
      state = AsyncValue.data(getGuessYouLikeData);
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}

/// user profile information
class GetUserProfileInformationNotifier extends StateNotifier<AsyncValue<UserProfileInformationModel>> {
  GetUserProfileInformationNotifier() : super(const AsyncValue.loading());

  Future fetchUserProfileInformation() async {
    try {
      final userProfileInformationData = await GetUserProfileInformation.getUserProfileInformationFetch();
      state = AsyncValue.data(userProfileInformationData);
    } catch (err) {
      state = AsyncValue.error(err, StackTrace.current);
    }
  }
}

/// payments
class PaymentsGoodsNotifier extends StateNotifier<AsyncValue<PaymentsModel>> {
  PaymentsGoodsNotifier() : super(const AsyncValue.loading());

  Future fetchPaymentsGoods() async {
    try {
      final paymentData = await PaymentsGoods.paymentsGoodsFetch();
      state = AsyncValue.data(paymentData);
    } catch (e) {
      state = AsyncValue.error(e, StackTrace.current);
    }
  }
}
